#include "comm.h"

#define LISTEN_PORT 10000

void str_echo(int sockfd, struct sockaddr *cli, socklen_t clilen);
int main(int ac, char *av[]){
    struct sockaddr_in addr;
    struct sockaddr_in cli;
    int socksrv, sockcli;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    addr.sin_port = htons(LISTEN_PORT);
    if((socksrv=socket(AF_INET, SOCK_DGRAM, 0))<0){
        err_sys();
    }
    bind(socksrv, (struct sockaddr*)&addr, sizeof(addr));
    str_echo(socksrv, (struct sockaddr*)&cli, sizeof(cli));
    return 0;
}

void str_echo(int sockfd, struct sockaddr *cli, socklen_t clilen){
    int n;
    char buf[MAXLINE];
    char ip[MAXLINE];
    struct sockaddr_in *peer;
    for(; ;){
        if((n=recvfrom(sockfd, buf, MAXLINE, 0, cli, &clilen))<0){
            err_sys();
        }
        buf[n] = 0;
        peer = (struct sockaddr_in*)cli;
        printf("Receive from %s:%d %s", inet_ntop(peer->sin_family, &peer->sin_addr, ip, MAXLINE), ntohs(peer->sin_port),buf);
        if((n=sendto(sockfd, buf, n, 0, cli, clilen))<0){
            err_sys();
        }
    }
}

